export const openDB = (dbName: string, version = 1) => {
  return new Promise((resolve, reject) => {
    // 兼容浏览器
    const indexedDB = window.indexedDB;
    let db;

    // 打开数据库,如果不存在则创建数据库
    const request = indexedDB.open(dbName, version);

    // 数据库打开成功的回调
    request.onsuccess = function (event: any) {
      db = event.target?.result; //数据库对象
      console.log("数据库打开成功");
      resolve(db);
    };

    // 数据库打开失败的回调
    request.onerror = function (event: any) {
      console.log("数据库打开失败！");
    };

    // 数据库更新的时候的回调
    request.onupgradeneeded = function (event: any) {
      // 数据库创建或升级的时候会触发
      db = event.target?.result; //数据库对象
      let objStore;

      // 创建数据表
      objStore = db.createObjectStore("flights", {
        keyPath: "file", //主键
        // autoIncrement: true  //实现自增
      });

      // 创建索引，方便在查询数据时根据索引进行查询
      // objStore.createIndex("id", "id", { unique: true });
      // objStore.createIndex("name", "name", { unique: false });
      // objStore.createIndex("age", "age", { unique: false });
    };
  });
};

//  添加数据
export const addData = (db: any, storeName: string, data: any) => {
  const request = db
    .transaction([storeName], "readwrite") //事务对象 指定表名称和操作模式（“只读”或“读写”）
    .objectStore(storeName) //仓库对象
    .add(data);

  request.onsuccess = function (e: any) {
    console.log("数据写入成功");
  };

  request.onerror = function (e: any) {
    console.log("数据写入失败！");
  };
};

// 通过主键查询数据
export const getDataByKey = (db: any, storeName: string, key: string) => {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction([storeName]); //事务
    const objectStore = transaction.objectStore(storeName); //仓库对象
    const request = objectStore.get(key); //通过主键获取数据
    // var request = objectStore.getAll(37);  //查询全部数据

    request.onsuccess = function (e: any) {
      resolve(request.result);
    };

    request.onerror = function (e: any) {
      console.log("查询失败！", e);
      reject(e);
    };
  });
};

// 通过游标查询数据
export const cursorGetData = (db: any, storeName: string) => {
  const list: any[] = [];
  const store = db
    .transaction([storeName], "readwrite") //事务
    .objectStore(storeName); //仓库对象
  const request = store.openCursor(); //指针对象

  // 游标开启成功，读取数据
  request.onsuccess = function (e: any) {
    const cursor = e.target.result;
    if (cursor) {
      list.push(cursor.value);
      cursor.continue(); //遍历存储对象中的所有内容
    } else {
      console.log("游标查询成功：");
    }
  };
};

// 通过索引查询数据
export const getDataByIndex = (
  db: any,
  storeName: string,
  indexName: string,
  indexValue: any
) => {
  const store = db
    .transaction([storeName], "readwrite") //事务
    .objectStore(storeName); //仓库对象
  const request = store.index(indexName).get(indexValue);

  request.onsuccess = (e: any) => {
    const result = e.target.result;
  };
  request.onerror = (e: any) => {
    alert("查询失败！");
  };
};

// 通过索引游标查询
export const cursorGetDataByIndex = (
  db: any,
  storeName: string,
  indexName: string,
  indexValue: string
) => {
  const list: any[] = [];
  const store = db
    .transaction([storeName], "readwrite") //事务
    .objectStore(storeName); //仓库对象
  const request = store
    .index(indexName) //索引对象
    .openCursor(IDBKeyRange.only(indexValue)); //指针没对象
  request.onsuccess = (e: any) => {
    const cursor = e.target.result;
    if (cursor) {
      list.push(cursor.value);
      cursor.continue(); //遍历存储对象中的所有内容
    } else {
      console.log("游标索引查询结果");
    }
  };
  request.onerror = function () {
    alert("查询失败！");
  };
};

// 通过游标和索引分页查询
export const cursorGetDataByIndexAndPage = (
  db: any,
  storeName: string,
  indexName: string,
  indexValue: string,
  page: number,
  pageSize: number
) => {
  const list: any[] = [];
  let counter = 0; //计数器
  let advanced = true; //是否跳过多少条查询
  const store = db
    .transaction([storeName], "readwrite") //事务
    .objectStore(storeName); //仓库对象
  const request = store
    .index(indexName) //索引对象
    .openCursor(IDBKeyRange.only(indexValue)); //指针没对象
  request.onsuccess = (e: any) => {
    let cursor = e.target.result;
    if (page > 1 && advanced) {
      advanced = false;
      cursor.advance((page - 1) * pageSize); //跳过多少条
      return;
    }
    if (cursor) {
      list.push(cursor.value);
      counter++;
      if (counter < pageSize) {
        cursor.continue(); //遍历存储对象中的所有内容
      } else {
        cursor = null;
      }
    } else {
      console.log("分页查询结果");
    }
  };
};

// 数据更新
export const updateDB = (db: any, storeName: string, data: any) => {
  const request = db
    .transaction([storeName], "readwrite") //事务
    .objectStore(storeName) //仓库对象
    .put(data);
  request.onsuccess = (e: any) => {
    console.log("数据更新成功");
  };
  request.onerror = () => {
    alert("数据更新失败！");
  };
};

// 数据删除
export const deleteDB = (db: any, storeName: string, id: number) => {
  const request = db
    .transaction([storeName], "readwrite") //事务
    .objectStore(storeName) //仓库对象
    .delete(id);
  request.onsuccess = (e: any) => {
    console.log("数据删除成功");
  };
  request.onerror = () => {
    console.log("数据删除失败！");
  };
};

// 通过索引游标删除数据
export const cursorDelete = (
  db: any,
  storeName: string,
  indexName: string,
  indexValue: string
) => {
  const store = db
    .transaction([storeName], "readwrite") //事务
    .objectStore(storeName); //仓库对象
  const request = store
    .index(indexName) //索引对象
    .openCursor(IDBKeyRange.only(indexValue)); //指针没对象
  request.onsuccess = (e: any) => {
    const cursor = e.target.result;
    let deleteRequest;
    if (cursor) {
      deleteRequest = cursor.delete(); // 请求删除当前项
      deleteRequest.onsuccess = (e: any) => {
        alert("游标删除该数据成功！");
      };
      deleteRequest.onerror = () => {
        alert("游标删除该数据失败！");
      };
      cursor.continue();
    }
  };
};

// 关闭数据库
export const closeDB = (db: any) => {
  db.close();
  alert("数据库已关闭！");
};
